<template>
  <el-dialog
    :title="title"
    :visible.sync="innerVisible"
    width="600px"
    @close="handleCancel"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="180px"
    >
      <el-form-item label="年月" prop="period">
        <!-- <el-select
          placeholder="请选择"
          v-model="form.year"
          clearable
          :disabled="isDetail"
        >
          <el-option
            v-for="item in yearList"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select> -->
        <el-date-picker
          v-model="form.period"
          type="month"
          placeholder="请选择"
          :disabled="isDetail"
        />
      </el-form-item>

      <el-form-item
        label="企业名称"
        prop="foreignInvestorName"
      >
        <el-select
          v-model.trim="form.foreignInvestorName"
          :disabled="isDetail"
          placeholder="请选择"
          filterable
          allow-create
          @change="handleSelectChange"
        >
          <el-option
            v-for="item in enterpriseOptions"
            :key="item.socialCode"
            :label="item.name"
            :value="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="统一社会信用代码"
        prop="foreignInvestorCode"
      >
        <el-input
          v-model.trim="form.foreignInvestorCode"
          placeholder="请输入"
          :disabled="isDetail || isExisting"
        />
      </el-form-item>

      <el-form-item label="本月完成FDI(万美元)">
        <el-input
          v-model="form.fdi"
          placeholder="请输入"
          :disabled="isDetail"
          type="number"
        />
      </el-form-item>

      <el-form-item
        label="关联招商项目"
        prop="businessProjectId"
      >
        <el-select
          v-model.trim="form.businessProjectId"
          :disabled="isDetail"
          placeholder="请选择"
          filterable
          :filter-method="filterMethodBusinessProjectId"
          v-loading="loading"
        >
          <el-option
            v-for="item in investTypeOptions"
            :key="item.pkid"
            :label="item.projectName"
            :value="item.pkid"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <div
      slot="footer"
      class="dialog-footer"
      v-if="!isDetail"
    >
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm"
        >确定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import {
  industryPlatTypeOptions,
  constructionStatusOptions,
  investTypeOptions
} from '@/utils/project/data'
import {
  civilTypeOptions,
  scienceFieldOptions
} from '@/utils/project/data'
import {
  investInfoQuery,
  enterpriseInfoQuery,
  addEnterpriseInfo
} from '@/api/dataManagement'
import dayjs from 'dayjs'

export default {
  name: 'ProgressDialog',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: '填写信息'
    },
    isDetail: {
      type: Boolean
    },
    currentData: {
      type: Object
    },
    isEdit: {
      type: Boolean
    }
  },
  data() {
    return {
      form: {
        pkid: '',
        fdi: '',
        period: '',
        foreignInvestorName: '',
        foreignInvestorCode: '',
        businessProjectId: ''
      },
      rules: {
        foreignInvestorName: [
          {
            required: true,
            message: '请输入企业名称',
            trigger: 'blur'
          }
        ],
        foreignInvestorCode: [
          {
            required: true,
            message: '请输入统一社会信用代码',
            trigger: 'change'
          }
        ],
        period: [
          {
            required: true,
            message: '请选择年月',
            trigger: 'blur'
          }
        ]
      },
      innerVisible: false,
      yearList: ['2025', '2024'],
      investTypeOptions: [],
      loading: false,
      enterpriseOptions: [],
      addEnterpriseInfo: {
        name: '',
        socialCode: '',
        type: '',
        enterpriseId: ''
      },
      isExisting: false
    }
  },
  watch: {
    visible(val) {
      this.innerVisible = val
    },
    innerVisible(val) {
      this.$emit('update:visible', val)
    },
    currentData(val) {
      this.getEnterpriseOptions()
      if (this.isEdit) {
        this.form = JSON.parse(JSON.stringify(val))
        this.form.period = val.period
          ? JSON.parse(
              JSON.stringify(
                dayjs(val.period).format('YYYY-MM')
              )
            )
          : ''
        this.isExisting = true
      } else {
        this.form = {
          pkid: '',
          fdi: '',
          period: '',
          foreignInvestorName: '',
          foreignInvestorCode: '',
          businessProjectId: ''
        }
        this.isExisting = false
      }
    }
  },
  computed: {
    industryPlatTypeOptions() {
      return industryPlatTypeOptions
    },
    constructionStatusOptions() {
      return constructionStatusOptions
    },
    civilTypeOptions() {
      return civilTypeOptions
    },
    scienceFieldOptions() {
      return scienceFieldOptions
    }
  },
  mounted() {
    this.getInvestInfo()
  },
  methods: {
    handleSelectChange(newValue) {
      const value = String(newValue).trim()
      this.isExisting = this.enterpriseOptions.some(
        (item) => item.name === value
      )
      if (!this.isExisting) {
        // 手动输入的新企业名称
        this.addEnterpriseInfo.name = value
        this.form.foreignInvestorName = value
        this.form.foreignInvestorCode = ''
      } else {
        // 选择现有企业
        const enterpriseInfo = this.enterpriseOptions.find(
          (item) => item.name === value
        )
        this.form.foreignInvestorCode =
          enterpriseInfo.socialCode
        this.form.foreignInvestorName = enterpriseInfo.name
        this.addEnterpriseInfo.enterpriseId =
          enterpriseInfo.pkid
      }
    },
    filterMethodBusinessProjectId(val) {
      const value = String(val).trim()
      const one = this.investTypeOptions.find((e) =>
        e.projectName.includes(value)
      )
      if (one) {
        this.form.businessProjectId = one.pkid
      }
    },
    getEnterpriseOptions() {
      enterpriseInfoQuery({
        pageIndex: 1,
        pageSize: 999
      }).then((res) => {
        if (res.success) {
          this.enterpriseOptions = res.data.list
        }
      })
    },
    getInvestInfo() {
      const params = {
        pageIndex: 1,
        pageSize: 999
      }
      this.loading = true
      investInfoQuery(params)
        .then((res) => {
          this.loading = false
          if (res.success) {
            this.investTypeOptions = res.data.list
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    handleCancel() {
      this.$emit('update:visible', false)
    },
    async handleConfirm() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            // 如果是新企业，先添加企业信息
            if (!this.isExisting) {
              this.addEnterpriseInfo.enterpriseId = ''
              this.addEnterpriseInfo.socialCode =
                this.form.foreignInvestorCode
              this.addEnterpriseInfo.type = '' // 外资企业可以设置默认类型或留空
              this.addEnterpriseInfo.name =
                this.form.foreignInvestorName
              // const enterpriseRes = await addEnterpriseInfo(this.addEnterpriseInfo)
              // if (!enterpriseRes.success) {
              //   this.$message.error(enterpriseRes.message || '企业信息保存失败')
              //   return
              // }
            }
            this.form.enterpriseId =
              this.addEnterpriseInfo.enterpriseId
            this.$emit('confirm', { ...this.form })
            // this.handleCancel()
          } catch (error) {
            this.$message.error('保存失败，请重试')
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/dialog.scss';
::v-deep .el-input__inner {
  width: 320px !important;
}
</style>
